package com.example.myapplication;

import android.content.Context;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class RootCommand {
    public static String runCommand(Context context,String command) {
//        Toast.makeText(context, "开始执行命令", Toast.LENGTH_SHORT).show();
        Process process = null;
        String result = "";
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            String line = null;
            while ((line = is.readLine()) != null) {
                result += line;
            }
            process.waitFor();
//            Toast.makeText(context, "命令执行结束", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
//            Toast.makeText(context, "IOException", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (InterruptedException e) {
//            Toast.makeText(context, "InterruptedException", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (process != null) {
                    process.destroy();
                }
        }
        return result;
    }
}

